package com.itlaoqi.thread;

import java.util.Random;
import java.util.concurrent.*;

public class Match3 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Runner3 liuxiang = new Runner3();
        liuxiang.setName("刘翔");
        Runner3 laoqi = new Runner3();
        laoqi.setName("老齐");
         Runner3 lufei = new Runner3();
        lufei.setName("路飞");

        //用于接受线程内部call方法返回值
        Future<Integer> retliuxiang = executorService.submit(liuxiang);//将这个对象放到线程池，线程池自动分配一个线程运行
        Future<Integer> retlaoqi = executorService.submit(laoqi);//将这个对象放到线程池，线程池自动分配一个线程运行
        Future<Integer> retlufei = executorService.submit(lufei);//将这个对象放到线程池，线程池自动分配一个线程运行
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        try {
            System.out.println("刘翔累计跑了" + retliuxiang.get() + "米");
            System.out.println("老齐累计跑了" + retlaoqi.get() + "米");
            System.out.println("路飞累计跑了" + retlufei.get() + "米");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

class Runner3 implements Callable<Integer>{

    private String name;

    public void setName(String name){
        this.name = name;
    }

    //实现Callable借口可以实现允许我们的线程返回值和跑出异常
    @Override
    public Integer call() throws Exception {
        Integer speed = new Random().nextInt(100);
        Integer distinct = 0;
        for (int i = 0;i<100;i++){
//            Thread.sleep(1000);
            distinct = i * speed;
            System.out.println(this.name + "已前进" + distinct + "米(" + speed + "米/秒)");
        }
        return distinct;
    }
}
